<template>
  <div class="flex flex-col h-full overflow-hidden max-h-[768px] max-w-[1320px] mx-auto">
    <AppHeader :show-back-button="true" class="flex-shrink-0"/>

    <main class="flex-grow flex flex-col overflow-hidden p-2 gap-2">
      <h2 class="page-title text-center text-base font-bold text-[var(--text-primary)] flex-shrink-0 mb-1">数据监控图表</h2>

      <!-- 头部控制区域 -->
      <div class="controls-header flex justify-between items-center flex-shrink-0 gap-2">
        <!-- 模式选择 -->
        <div class="flex gap-1">
          <button
            @click="switchMode('realtime')"
            class="px-2 py-1 rounded-md text-xs font-medium"
            :class="chartMode === 'realtime' ? 'bg-[var(--accent-blue)] text-white' : 'bg-gray-100 text-[var(--text-primary)] hover:bg-gray-200'"
          >
            <i class="fas fa-bolt mr-1"></i>实时数据
          </button>
          <button
            @click="switchMode('history')"
            class="px-2 py-1 rounded-md text-xs font-medium"
            :class="chartMode === 'history' ? 'bg-[var(--accent-blue)] text-white' : 'bg-gray-100 text-[var(--text-primary)] hover:bg-gray-200'"
          >
            <i class="fas fa-history mr-1"></i>历史数据
          </button>
        </div>

        <!-- 时间范围 -->
        <div class="flex items-center gap-1">
          <span class="text-xs font-medium text-[var(--text-secondary)]">时间范围:</span>
          <div class="flex gap-1">
            <button
              v-for="(option, index) in timeRangeOptions"
              :key="index"
              @click="selectTimeRange(option.value)"
              class="px-1.5 py-0.5 text-xs rounded-md"
              :class="timeRange === option.value ? 'bg-[var(--accent-blue)] text-white' : 'bg-gray-100 text-[var(--text-primary)] hover:bg-gray-200'"
              :disabled="isCollecting"
            >
              {{ option.label }}
            </button>
          </div>
        </div>

        <!-- 条码搜索 -->
        <div class="flex items-center gap-1">
          <label for="sn-search" class="text-xs font-medium text-[var(--text-secondary)]">条码:</label>
          <input type="text" id="sn-search" v-model="searchSN"
                 placeholder="输入条码"
                 class="px-1.5 py-0.5 border border-[var(--border-color)] rounded-md text-xs bg-[#f9fafb] w-40 focus:outline-none focus:border-[var(--accent-blue)]"
                 :disabled="isCollecting">
        </div>
      </div>

      <!-- 地址选择和控制参数 -->
      <div class="controls-area bg-[var(--bg-secondary)] p-2 rounded-md flex flex-col gap-2 border border-[var(--border-color)] shadow-sm flex-shrink-0">
        <!-- 地址选择 -->
        <div class="flex gap-2 items-start">
          <span class="text-xs font-medium text-[var(--text-secondary)] pt-1 w-16">PLC 地址:</span>
          <div class="flex gap-1 items-start flex-grow">
            <input
              type="text"
              v-model="addressSearchTerm"
              @input="filterAddresses"
              placeholder="搜索..."
              class="px-1.5 py-0.5 border border-[var(--border-color)] rounded-md text-xs bg-[#f9fafb] focus:outline-none focus:border-[var(--accent-blue)] w-24"
            />
            <div class="h-[70px] overflow-y-auto border border-[var(--border-color)] rounded-md p-1 bg-[#f9fafb] flex-grow">
              <div class="grid grid-cols-3 gap-y-0.5 gap-x-2 h-full">
                <div
                  v-for="(addr, index) in availableAddresses"
                  :key="addr.id"
                  class="flex items-center gap-0.5"
                  :class="{ 'hidden': !addr.visible }"
                >
                  <input
                    type="checkbox"
                    :id="`addr-${addr.id}`"
                    :value="addr.id"
                    v-model="selectedAddressIds"
                    @change="handleAddressSelectionChange"
                    class="w-3 h-3 accent-[var(--accent-blue)]"
                    :disabled="isCollecting"
                  />
                  <label :for="`addr-${addr.id}`" class="text-xs text-[var(--text-primary)] whitespace-nowrap cursor-pointer overflow-hidden text-ellipsis">
                    {{ addr.propertyName }} ({{ addr.description }})
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 控制参数和按钮 -->
        <div class="flex flex-wrap gap-2 items-center">
          <!-- <div class="flex items-center gap-1">
            <label for="update-interval" class="text-xs font-medium text-[var(--text-secondary)]">刷新(ms):</label>
            <input type="number" id="update-interval" v-model.number="updateIntervalMs"
                   class="px-1.5 py-0.5 border border-[var(--border-color)] rounded-md text-xs bg-[#f9fafb] w-16 focus:outline-none focus:border-[var(--accent-blue)]"
                   min="100" max="5000" step="100" :disabled="isCollecting">
          </div>
          <div class="flex items-center gap-1">
            <label for="max-data-points" class="text-xs font-medium text-[var(--text-secondary)]">数据点:</label>
            <input type="number" id="max-data-points" v-model.number="maxDataPoints"
                   class="px-1.5 py-0.5 border border-[var(--border-color)] rounded-md text-xs bg-[#f9fafb] w-16 focus:outline-none focus:border-[var(--accent-blue)]"
                   min="10" max="2000" step="10" :disabled="isCollecting">
          </div> -->

          <!-- 按钮组 -->
          <div class="flex items-center gap-1 ml-auto">
            <!-- 实时模式按钮 -->
            <button
              v-if="chartMode === 'realtime'"
              @click="toggleCollection"
              id="btn-start-stop"
              class="hmi-button px-2 py-1 rounded-md text-xs font-medium flex items-center gap-1"
              :class="isCollecting ? 'hmi-button-danger' : 'hmi-button-success'"
              :disabled="selectedAddressIds.length === 0 && !isCollecting"
            >
              <i :class="isCollecting ? 'fas fa-stop' : 'fas fa-play'"></i>
              {{ isCollecting ? '停止' : '开始' }}
            </button>

            <!-- 历史模式按钮 -->
            <button
              v-if="chartMode === 'history'"
              @click="loadHistoryData"
              id="btn-load-history"
              class="hmi-button hmi-button-success px-2 py-1 rounded-md text-xs font-medium flex items-center gap-1"
              :disabled="selectedAddressIds.length === 0"
            >
              <i class="fas fa-search"></i>
              查询
            </button>

            <!-- 导出按钮 -->
            <button
              @click="exportChartData"
              class="hmi-button hmi-button-secondary px-2 py-1 rounded-md text-xs font-medium flex items-center gap-1"
              :disabled="!hasChartData"
            >
              <i class="fas fa-download"></i> 导出
            </button>

            <!-- 清空按钮 -->
            <button 
              @click="clearChart" 
              id="btn-clear-chart"
              class="hmi-button hmi-button-secondary px-2 py-1 rounded-md text-xs font-medium flex items-center gap-1"
            >
              <i class="fas fa-trash"></i> 清空
            </button>
          </div>
        </div>
      </div>

      <!-- 图表信息栏 - 显示SN条码 -->
      <div v-if="currentDataSN || lastUpdateTime" class="chart-info bg-[var(--bg-secondary)] p-1.5 rounded-md flex justify-between items-center border border-[var(--border-color)] shadow-sm flex-shrink-0">
        <div class="flex items-center gap-2">
          <span v-if="currentDataSN" class="text-xs font-medium">
            <i class="fas fa-barcode text-[var(--accent-blue)]"></i>
            <span class="ml-1">条码: </span>
            <span class="text-[var(--text-primary)] font-bold">{{ currentDataSN }}</span>
          </span>
        </div>
        <div v-if="lastUpdateTime" class="text-xs text-[var(--text-secondary)]">
          <i class="fas fa-clock"></i>
          <span class="ml-1">更新时间: {{ formatDateTime(lastUpdateTime) }}</span>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="chart-container flex-grow bg-[var(--bg-secondary)] rounded-md border border-[var(--border-color)] shadow-sm p-2 relative overflow-hidden min-h-[250px]">
        <div v-if="loading" class="absolute inset-0 flex items-center justify-center bg-white bg-opacity-80 z-30">
          <div class="text-center">
            <i class="fas fa-spinner fa-spin text-[var(--accent-blue)] text-xl mb-1"></i>
            <p class="text-[var(--text-secondary)] text-sm">加载数据中...</p>
          </div>
        </div>
        <canvas ref="chartCanvas" id="realtime-chart"></canvas>
        <div v-if="selectedAddressIds.length === 0"
             class="absolute inset-0 flex items-center justify-center bg-white bg-opacity-80 text-[var(--text-secondary)] text-center text-sm font-medium z-20">
          请选择至少一个PLC地址以开始监控。
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, onBeforeUnmount, computed, watch} from 'vue';
import Chart from 'chart.js/auto'; // Chart.js v3+
import 'chartjs-adapter-date-fns'; // 日期适配器
import AppHeader from '@/components/AppHeader.vue'; // 导入 AppHeader 组件
import plcAddressStore from '@/api/plcAddress'; // 导入PLC地址API
import { getDataByTimeRange, getLatestData, exportData } from '@/api/chartData'; // 导入图表数据API

// --- 页面状态 ---
const loading = ref(false); // 加载状态
const chartCanvas = ref(null); // 用于获取 canvas 元素的 ref
let chartInstance = null; // Chart.js 实例
let dataIntervalId = null; // 数据采集定时器 ID
const isCollecting = ref(false); // 是否正在采集数据
const chartMode = ref('realtime'); // 图表模式：'realtime' 或 'history'
const searchSN = ref(''); // 条码搜索
const timeRange = ref('1hour'); // 时间范围
const hasChartData = ref(false); // 是否有图表数据
let lastDataTimestamp = null; // 用于存储最后一条数据的时间戳
const currentDataSN = ref(''); // 用于显示当前数据的SN条码
const lastUpdateTime = ref(null); // 最后更新时间

// 可用的 PLC 地址列表
const availableAddresses = reactive([]); // 从API获取的PLC地址列表
const addressSearchTerm = ref(''); // 地址搜索关键词
const selectedAddressIds = ref([]); // 选中的地址 ID 数组

// 控制参数
const updateIntervalMs = ref(500); // 刷新间隔
const maxDataPoints = ref(500); // 最大数据点

// 常用的单位信息，根据地址类型推断
const unitByType = {
  'float': '',
  'int': '',
  'tension': 'N',
  'speed': 'rpm',
  'resistance': 'Ω',
  'count': '圈'
};

// 时间范围选项
const timeRangeOptions = [
  { label: '1小时', value: '1hour' },
  { label: '6小时', value: '6hours' },
  { label: '12小时', value: '12hours' },
  { label: '24小时', value: '24hours' }
];

// 计算属性：时间范围的开始和结束时间
const timeRangeValues = computed(() => {
  const now = Date.now();

  switch (timeRange.value) {
    case '1hour':
      return { start: now - 60 * 60 * 1000, end: now };
    case '6hours':
      return { start: now - 6 * 60 * 60 * 1000, end: now };
    case '12hours':
      return { start: now - 12 * 60 * 60 * 1000, end: now };
    case '24hours':
      return { start: now - 24 * 60 * 60 * 1000, end: now };
    default:
      return { start: now - 60 * 60 * 1000, end: now };
  }
});

// 图表线颜色
const lineColors = [
  'var(--accent-blue)', 'var(--accent-teal)', 'var(--accent-purple)',
  'var(--accent-orange)', 'var(--accent-pink)', 'var(--status-gray)'
];
const lineBgColors = [
  'rgba(59, 130, 246, 0.1)', 'rgba(20, 184, 166, 0.1)', 'rgba(139, 92, 246, 0.1)',
  'rgba(249, 115, 22, 0.1)', 'rgba(236, 72, 153, 0.1)', 'rgba(107, 114, 128, 0.1)'
];

// --- 方法 ---

// 过滤地址列表
const filterAddresses = () => {
  const searchTerm = addressSearchTerm.value.toLowerCase();
  availableAddresses.forEach(addr => {
    const itemSearchTerm = `${addr.address.toLowerCase()} ${addr.description.toLowerCase()} ${addr.propertyName?.toLowerCase() || ''}`;
    addr.visible = itemSearchTerm.includes(searchTerm);
  });
};

// 根据地址描述猜测合适的单位
const guessUnit = (address) => {
  const description = (address.description || '').toLowerCase();
  
  if (description.includes('张力')) {
    return 'N';
  } else if (description.includes('速度')) {
    return 'rpm';
  } else if (description.includes('电阻')) {
    return 'Ω';
  } else if (description.includes('圈数')) {
    return '圈';
  }
  
  // 无法猜测时返回空字符串
  return '';
};

// 初始化或更新图表 - 优化版本
const initializeChart = (selectedAddressesData) => {
  if (!chartCanvas.value) {
    console.error("Canvas元素未找到!");
    return;
  }
  const ctx = chartCanvas.value.getContext('2d');
  if (!ctx) {
    console.error("Canvas上下文未找到!");
    return;
  }

  // 销毁旧图表实例（如果存在）
  if (chartInstance) {
    chartInstance.destroy();
  }

  // 根据选中的地址创建数据集
  const datasets = selectedAddressesData.map((addr, index) => {
    const colorIndex = index % lineColors.length;
    const unit = guessUnit(addr);
    
    // 构建标签文本
    const labelText = addr.propertyName 
      ? `${addr.propertyName} (${addr.description}${unit ? ' - ' + unit : ''})`
      : `${addr.address} (${addr.description})`;

    return {
      label: labelText,
      data: [], // 数据点数组
      borderColor: lineColors[colorIndex],
      backgroundColor: lineBgColors[colorIndex],
      borderWidth: 1.5,
      tension: 0.1,
      pointRadius: chartMode.value === 'realtime' ? 0 : 1, // 实时模式不显示点，历史模式显示小点
      fill: false, // 不填充区域
      address: addr.address, // 存储PLC地址
      propertyName: addr.propertyName, // 存储属性名，用于从data_values中获取数据
      unit: unit, // 存储单位
      yAxisID: 'yAnalog', // 默认使用模拟量Y轴
      addressId: addr.id // 存储地址ID
    };
  });

  // 创建新图表实例，优化渲染性能的配置
  chartInstance = new Chart(ctx, {
    type: 'line',
    data: {
      datasets: datasets
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      parsing: false, // 数据已经格式化，跳过解析
      normalized: true, // 数据已经标准化
      animation: false, // 禁用动画以提高性能
      layout: {
        padding: {
          top: 5,
          right: 5,
          bottom: 5,
          left: 5
        }
      },
      scales: {
        x: {
          type: 'time',
          time: {
            unit: chartMode.value === 'realtime' ? 'second' : 'minute',
            displayFormats: {
              second: 'HH:mm:ss',
              minute: 'HH:mm'
            },
            tooltipFormat: 'yyyy/MM/dd HH:mm:ss'
          },
          title: {
            display: false // 在紧凑模式下不显示轴标题
          },
          ticks: {
            maxRotation: 0,
            autoSkip: true,
            maxTicksLimit: 6, // 减少刻度数量
            color: 'var(--text-primary)',
            font: {
              size: 10 // 更小的字体
            }
          },
          grid: {
            display: true,
            color: 'rgba(0, 0, 0, 0.05)'
          }
        },
        yAnalog: {
          type: 'linear',
          display: true,
          position: 'left',
          beginAtZero: false, // Y轴不强制从0开始
          title: {
            display: false // 在紧凑模式下不显示轴标题
          },
          ticks: {
            color: 'var(--text-primary)',
            font: {
              size: 10 // 更小的字体
            },
            maxTicksLimit: 6 // 减少刻度数量
          },
          grid: {
            color: 'rgba(0, 0, 0, 0.05)'
          }
        }
      },
      plugins: {
        legend: {
          display: true,
          position: 'top',
          align: 'start',
          labels: {
            boxWidth: 10,
            boxHeight: 10,
            usePointStyle: true,
            color: 'var(--text-primary)',
            font: {
              size: 10 // 更小的字体
            },
            padding: 6 // 减少填充
          }
        },
        tooltip: {
          mode: 'index',
          intersect: false,
          titleFont: {
            size: 10
          },
          bodyFont: {
            size: 10
          },
          callbacks: {
            label: function(context) {
              const dataset = context.dataset;
              const value = context.raw.y;
              const unit = dataset.unit || '';
              return `${dataset.label.split('(')[0].trim()}: ${value.toFixed(2)}${unit ? ' ' + unit : ''}`;
            }
          }
        }
      },
      elements: {
        line: {
          borderWidth: 1.5,
          tension: 0.1
        },
        point: {
          radius: chartMode.value === 'realtime' ? 0 : 1
        }
      },
      interaction: {
        mode: 'nearest',
        axis: 'x',
        intersect: false
      }
    }
  });
  
  hasChartData.value = false;
};

// 处理地址选择变化
const handleAddressSelectionChange = () => {
  // 当选中的地址变化时，如果正在采集，先停止采集
  if (isCollecting.value) {
    toggleCollection(); // 停止采集
  }
  
  if (selectedAddressIds.value.length > 0) {
    const selectedData = selectedAddressIds.value.map(id => {
      return availableAddresses.find(a => a.id === id);
    }).filter(Boolean);
    
    initializeChart(selectedData);
  } else {
    // 如果没有选中任何地址，清空图表
    if (chartInstance) {
      chartInstance.destroy();
      chartInstance = null;
    }
  }
};

// 切换图表模式 (实时/历史)
const switchMode = (mode) => {
  if (chartMode.value === mode) return;
  
  // 如果正在采集，先停止采集
  if (isCollecting.value) {
    toggleCollection();
  }
  
  chartMode.value = mode;
  
  // 清空图表
  if (chartInstance) {
    chartInstance.data.datasets.forEach(dataset => {
      dataset.data = [];
    });
    chartInstance.update('none');
  }
  
  hasChartData.value = false;
  lastDataTimestamp = null; // 重置时间戳记录
  
  // 如果有选中的地址，重新初始化图表
  if (selectedAddressIds.value.length > 0) {
    const selectedData = selectedAddressIds.value.map(id => {
      return availableAddresses.find(a => a.id === id);
    }).filter(Boolean);
    
    initializeChart(selectedData);
  }
};

// 选择时间范围
const selectTimeRange = (rangeValue) => {
  timeRange.value = rangeValue;
  
  // 如果当前是历史模式，并且有选中的地址，自动重新加载数据
  if (chartMode.value === 'history' && selectedAddressIds.value.length > 0) {
    loadHistoryData();
  }
};

// 格式化日期时间显示
const formatDateTime = (timestamp) => {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 从API获取实时数据 - 优化版本
const fetchData = async () => {
  if (!chartInstance || !isCollecting.value || chartInstance.data.datasets.length === 0) return;

  try {
    const now = Date.now();
    
    // 获取最新数据
    const latestData = await getLatestData(1, searchSN.value || null);
    
    if (!latestData || latestData.length === 0) {
      console.warn('未找到最新数据');
      return;
    }
    
    // 检查时间戳是否变化
    const currentTimestamp = latestData[0].timestamp;
    
    // 如果时间戳未变化，则不更新图表
    if (lastDataTimestamp === currentTimestamp) {
      console.log('数据时间戳未变化，跳过图表更新');
      return;
    }
    
    // 更新最后一条数据的时间戳
    lastDataTimestamp = currentTimestamp;
    
    // 更新SN条码和更新时间显示
    currentDataSN.value = latestData[0].sn || '';
    lastUpdateTime.value = currentTimestamp;
    
    const dataValues = latestData[0].data_values;
    let needsUpdate = false;
    
    // 批量处理所有数据更新，而不是每个数据点单独更新
    let datasetUpdates = [];
    
    // 更新图表数据
    chartInstance.data.datasets.forEach((dataset, index) => {
      // 使用propertyName从data_values中获取数据
      const propertyName = dataset.propertyName;
      
      // 如果data_values中有对应的字段值
      if (propertyName && dataValues[propertyName] !== undefined) {
        const newPoint = {
          x: currentTimestamp, // 使用数据的实际时间戳，而不是当前时间
          y: parseFloat(dataValues[propertyName]) || 0
        };
        
        // 仅当有数据时才添加
        dataset.data.push(newPoint);
        needsUpdate = true;
        
        // 限制数据点数量
        if (dataset.data.length > maxDataPoints.value) {
          dataset.data.shift(); // 移除最老的数据点
        }
        
        datasetUpdates.push({ index, data: dataset.data });
      }
    });
    
    // 仅当有数据更新时才更新图表
    if (needsUpdate) {
      // 使用requestAnimationFrame减轻主线程负担
      requestAnimationFrame(() => {
        chartInstance.update('none'); // 更新图表，'none' 表示不使用动画
      });
      hasChartData.value = true;
    }
  } catch (error) {
    console.error('获取实时数据失败:', error);
    // 错误处理：在连续多次错误后暂停采集
    if (isCollecting.value) {
      errorCount++;
      if (errorCount > 5) {
        console.error('连续多次获取数据失败，暂停监控');
        toggleCollection(); // 暂停监控
        alert('由于连续多次获取数据失败，监控已自动暂停');
        errorCount = 0;
      }
    }
  }
};

// 加载历史数据 - 优化版本
const loadHistoryData = async () => {
  if (selectedAddressIds.value.length === 0) {
    console.warn('未选择任何PLC地址');
    return;
  }
  
  try {
    loading.value = true;
    
    const { start, end } = timeRangeValues.value;
    
    // 获取历史数据
    const historyData = await getDataByTimeRange(start, end, searchSN.value || null);
    
    if (!historyData || historyData.length === 0) {
      console.warn('指定时间范围内未找到数据');
      loading.value = false;
      return;
    }
    
    // 确保图表已初始化
    if (!chartInstance) {
      const selectedData = selectedAddressIds.value.map(id => {
        return availableAddresses.find(a => a.id === id);
      }).filter(Boolean);
      
      initializeChart(selectedData);
    }
    
    // 清空现有数据
    chartInstance.data.datasets.forEach(dataset => {
      dataset.data = [];
    });
    
    // 数据降采样处理，避免过多数据点导致性能问题
    const maxPointsPerSeries = 500; // 每条线最多显示的点数
    let samplingFactor = 1;
    
    if (historyData.length > maxPointsPerSeries) {
      samplingFactor = Math.ceil(historyData.length / maxPointsPerSeries);
    }
    
    // 如果有数据，显示第一条数据的SN
    if (historyData.length > 0) {
      currentDataSN.value = historyData[0].sn || '';
      lastUpdateTime.value = historyData[0].timestamp;
    }
    
    // 填充历史数据（使用降采样）
    for (let i = 0; i < historyData.length; i += samplingFactor) {
      const record = historyData[i];
      const timestamp = record.timestamp;
      const dataValues = record.data_values;
      
      chartInstance.data.datasets.forEach(dataset => {
        // 使用propertyName从data_values获取数据
        const propertyName = dataset.propertyName;
        
        // 如果data_values中有对应的字段值
        if (propertyName && dataValues[propertyName] !== undefined) {
          dataset.data.push({
            x: timestamp,
            y: parseFloat(dataValues[propertyName]) || 0
          });
        }
      });
    }
    
    // 使用requestAnimationFrame来减轻主线程负担
    requestAnimationFrame(() => {
      chartInstance.update('none');
    });
    
    hasChartData.value = true;
    
  } catch (error) {
    console.error('加载历史数据失败:', error);
    alert(`加载历史数据失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// 错误计数器
let errorCount = 0;

// 开始/停止采集
const toggleCollection = () => {
  if (selectedAddressIds.value.length === 0 && !isCollecting.value) {
    alert("请至少选择一个PLC地址进行监控。");
    return;
  }
  
  isCollecting.value = !isCollecting.value;
  errorCount = 0; // 重置错误计数
  
  if (isCollecting.value) {
    // 开始采集
    const intervalMs = updateIntervalMs.value || 1000;
    
    // 清除任何可能存在的定时器
    if (dataIntervalId) {
      clearInterval(dataIntervalId);
    }
    
    dataIntervalId = setInterval(fetchData, intervalMs);
    fetchData(); // 立即采集一次
  } else {
    // 停止采集
    if (dataIntervalId) {
      clearInterval(dataIntervalId);
      dataIntervalId = null;
    }
  }
};

// 清空图表
const clearChart = () => {
  if (isCollecting.value) {
    toggleCollection(); // 先停止采集
  }
  
  if (chartInstance) {
    chartInstance.data.datasets.forEach(dataset => {
      dataset.data = [];
    });
    chartInstance.update('none');
  }
  
  hasChartData.value = false;
  lastDataTimestamp = null; // 重置时间戳记录
  currentDataSN.value = ''; // 清空SN显示
  lastUpdateTime.value = null; // 清空更新时间
  console.log('图表已清空');
};

// 导出图表数据
const exportChartData = async () => {
  try {
    const { start, end } = timeRangeValues.value;
    const csv = await exportData(start, end, searchSN.value || null);
    
    if (!csv || csv.trim() === '') {
      alert('没有可导出的数据');
      return;
    }
    
    // 创建下载链接
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `chart_data_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
  } catch (error) {
    console.error('导出数据失败:', error);
    alert(`导出数据失败: ${error.message || '未知错误'}`);
  }
};

// 加载PLC地址列表
const loadPlcAddresses = async () => {
  try {
    loading.value = true;
    // 从API获取PLC地址列表
    const addresses = await plcAddressStore.getAll();
    if (Array.isArray(addresses) && addresses.length > 0) {
      // 清空现有地址
      availableAddresses.length = 0;
      
      // 添加新地址到列表，并设置visible属性
      addresses.forEach(addr => {
        // 仅添加category为realtime的地址
        if (addr.category === 'realtime') {
          availableAddresses.push({
            ...addr,
            visible: true  // 用于过滤显示
          });
        }
      });
      
      console.log(`已加载 ${availableAddresses.length} 个监控地址`);
    } else {
      console.warn('没有找到PLC地址或地址列表为空');
    }
    
    // 应用过滤器
    filterAddresses();
  } catch (error) {
    console.error('加载PLC地址列表失败:', error);
    alert(`加载PLC地址列表失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

// --- 生命周期钩子 ---
onMounted(async () => {
  console.log('图表页面已挂载');
  
  // 加载PLC地址列表
  await loadPlcAddresses();
});

onBeforeUnmount(() => {
  console.log('图表页面卸载中');
  
  // 组件卸载前清理定时器和图表实例
  if (dataIntervalId) {
    clearInterval(dataIntervalId);
    dataIntervalId = null;
  }
  
  if (chartInstance) {
    chartInstance.destroy();
    chartInstance = null;
  }
  
  isCollecting.value = false;
});

// 监听选中地址的变化
watch(selectedAddressIds, () => {
  handleAddressSelectionChange();
});

// 监听刷新间隔的变化
watch(updateIntervalMs, (newInterval) => {
  if (isCollecting.value && dataIntervalId) {
    // 更新采集间隔
    clearInterval(dataIntervalId);
    dataIntervalId = setInterval(fetchData, newInterval);
  }
});
</script>

<style scoped>
/* 紧凑型图表组件样式 */

/* 确保在800*600屏幕上显示完整 */
:deep(.chart-js-container) {
  max-height: 250px !important;
}

/* 按钮样式 */
.hmi-button {
  transition: all 0.15s ease;
}

.hmi-button-success {
  background-color: var(--accent-green, #10b981);
  color: white;
}

.hmi-button-success:hover:not(:disabled) {
  background-color: var(--accent-green-dark, #059669);
}

.hmi-button-danger {
  background-color: var(--accent-red, #ef4444);
  color: white;
}

.hmi-button-danger:hover:not(:disabled) {
  background-color: var(--accent-red-dark, #dc2626);
}

.hmi-button-secondary {
  background-color: var(--bg-tertiary, #e5e7eb);
  color: var(--text-primary);
}

.hmi-button-secondary:hover:not(:disabled) {
  background-color: var(--bg-tertiary-dark, #d1d5db);
}

.hmi-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 优化小屏幕上的滚动条 */
.address-checkbox-container::-webkit-scrollbar {
  width: 4px;
}

.address-checkbox-container::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

/* 确保图表区域可以正确拉伸填充可用空间 */
.chart-container {
  min-height: 250px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 紧凑型输入框 */
input[type="text"],
input[type="number"] {
  height: 1.75rem;
}

/* 在紧凑视图下确保不会显示横向滚动条 */
main {
  max-width: 100%;
  overflow-x: hidden;
}
</style>